package com.jghz.autoconfigure.hibernate;

import org.hibernate.EmptyInterceptor;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.orm.hibernate3.HibernateExceptionTranslator;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.bstek.bdf2.core.orm.DataSourceRepository;
import com.bstek.bdf2.core.orm.hibernate.HibernateSessionFactory;
import com.jghz.autoconfigure.dorado.DoradoAutoConfiguration;
import com.jghz.configure.DataSourceConfiguration;

@Configuration
@ConditionalOnClass(DataSourceConfiguration.class)
@AutoConfigureAfter(DoradoAutoConfiguration.class)
@Import(DataSourceConfiguration.class)
@EnableTransactionManagement
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class HibernateAutoConfiguration {

	@Autowired
	private DataSourceRepository dataSourceRepository;

	@Bean
	@ConfigurationProperties(prefix = "entity")
	public EmptyInterceptor customEmptyInterceptor() {
		return new CustomEmptyInterceptor();

	}

	@Bean
	public HibernateExceptionTranslator hibernateExceptionTranslator() {
		return new HibernateExceptionTranslator();
	}

	@Bean
	public HibernateSessionFactory sessionFactory() {
		String defaultName = dataSourceRepository.getDefaultDataSourceName();
		HibernateSessionFactory sessionFactory = new HibernateSessionFactory();
		sessionFactory.setDataSourceName(defaultName);
		sessionFactory.setAsDefault(true);
		sessionFactory.setDataSource(dataSourceRepository.getDataSources().get(defaultName));
		sessionFactory.setPackagesToScan(new String[] { "com.**.entity*" });
		sessionFactory.setHibernateProperties(hibernateProps().toProperties());
		sessionFactory.setUseTransactionAwareDataSource(true);
		sessionFactory.setEntityInterceptor(customEmptyInterceptor());
		return sessionFactory;
	}
	// "com.bstek.uflo.model*"

	@Bean
	@Autowired
	public HibernateTransactionManager transactionManager(SessionFactory s) {
		HibernateTransactionManager txManager = new HibernateTransactionManager();
		txManager.setSessionFactory(s);
		return txManager;
	}

	@Bean
	@ConfigurationProperties(prefix = "hibernate")
	public HibernateProps hibernateProps() {
		return new HibernateProps();
	}
}
